from django.shortcuts import render
from django.views import View
import json
from django.http import JsonResponse
from django_redis import get_redis_connection
import base64
import pickle

from apps.goods.models import SKU
import logging

logger = logging.getLogger('django')


# Create your views here.

class CreateCartView(View):

    def delete(self, request):
        json_dict = json.loads(request.body.decode())

        sku_id = json_dict.get('sku_id')

        user = request.user
        response = JsonResponse({'code': 0, 'errmsg': '删除成功'})

        if user.is_authenticated:
            redis_conn = get_redis_connection()
            pl = redis_conn.pipeline()
            pl.hdel('cart_%s' % user.id, sku_id)
            pl.srem('selected_%s' % user.id, sku_id)
            pl.execute()

        else:
            cart_str = request.COOKIES.get('carts')

            if cart_str is None:
                cart_dict = {}
            else:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))

            if sku_id in cart_dict:
                del cart_dict[sku_id]
                # 将字典转成bytes,再将bytes转成base64的bytes,最后将bytes转字符串
                cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()
                # 响应结果并将购物车数据写入到cookie
                response.set_cookie('carts', cart_data)

        return response

    def put(self, request):
        json_dict = json.loads(request.body.decode())

        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        if not all([sku_id, count]):
            return JsonResponse({'code': 200, 'errmsg': '缺少必传参数'})

        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            return JsonResponse({'code': 200, 'errmsg': 'sku不存在'})

        try:
            count = int(count)
        except Exception as e:
            return JsonResponse({'code': 200, 'errmsg': 'count格式有误'})

        user = request.user
        response = JsonResponse({
            'code': 0,
            'errmsg': '添加购物车成功',
            'cart_sku': {
                'id': sku_id,
                'count': count,
                'selected': selected
            }
        })

        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            pl.hset('cart_%s' % user.id, sku_id, count)
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            else:
                pl.srem('selected_%s' % user.id, sku_id)
            pl.execute()

        else:
            cart_str = request.COOKIES.get('carts')

            if cart_str is None:
                cart_dict = {}
            else:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))

            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            cart_str_response = base64.b64encode(pickle.dumps(cart_dict)).decode()

            response.set_cookie('carts', cart_str_response)

        return response

    def get(self, request):
        '''
        'id':sku.id,
                'name':sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'selected': cart_dict.get(sku.id).get('selected'),
                'default_image_url':sku.default_image_url,
                'price':sku.price,
                'amount':sku.price * cart_dict.get(sku.id).get('count'),
        '''

        user = request.user

        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            item_dict = redis_conn.hgetall('cart_%s' % user.id)
            # print(cart_dict)
            selected_set = redis_conn.smembers('selected_%s' % user.id)

            cart_dict = {}
            for sku_id, count in item_dict.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in selected_set
                }

        else:
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

        skus_id = cart_dict.keys()
        skus = SKU.objects.filter(id__in=skus_id)

        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'selected': cart_dict.get(sku.id).get('selected'),
                'default_image_url': sku.default_image.url,
                'price': sku.price,
                'amount': sku.price * cart_dict.get(sku.id).get('count'),
            })

        return JsonResponse({
            'code': 0,
            'errmsg': 'OK',
            'cart_skus': cart_skus
        })

    def post(self, request):

        json_dict = json.loads(request.body.decode())

        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        if not all([sku_id, count]):
            return JsonResponse({'code': 200, 'errmsg': '缺少必传参数'})

        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            return JsonResponse({'code': 200, 'errmsg': 'sku不存在'})

        try:
            count = int(count)
        except Exception as e:
            return JsonResponse({'code': 200, 'errmsg': 'count格式有误'})

        user = request.user

        response = JsonResponse({'code': 0, 'errmsg': '添加购物车成功'})

        if user.is_authenticated:
            # 登录用户购物车保存在redis
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()

            pl.hset('cart_%s' % user.id, sku_id, count)
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            pl.execute()

        else:
            # 未登录用户的购物车保存在cookie
            cart_str = request.COOKIES.get('carts')

            if cart_str is None:
                cart_dict = {}
            else:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))

            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            cart_str_response = base64.b64encode(pickle.dumps(cart_dict)).decode()

            response.set_cookie('carts', cart_str_response)

        return response
